﻿using CommonIoC;
using Fungus;
using GDGeek;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class SceneLoadManager : Singleton<SceneLoadManager>
{
    void Start()
    {
       // prev_door = DoorType.NullDoor;
        DontDestroyOnLoad(this);
    }

    public void TestFunc()
    {
        Debug.Log("初始化 SceneLoadManager");
    }


    /// <summary>
    /// 前一个场景
    /// </summary>
    private string prev_scene;

    private string prev_door;
    /// <summary>
    /// 现在的场景
    /// </summary>
    private string now_scene;
    /// <summary>
    /// 下一个要跳转的场景
    /// </summary>
    private string next_scene;

    /// <summary>
    /// 触发战斗的原始场景
    /// </summary>
    private string join_battle_sceneName;


    private Vector3 join_battle_pos;
    /// <summary>
    /// 需要跳转到下一个场景的时候，，，玩家的坐标
    /// </summary>
    private Vector3 next_scene_player_pos;

    /// <summary>
    /// 触发战斗的Key,,也就是上一次战斗的key
    /// </summary>
    private string last_join_battle_key;
    /// <summary>
    /// 触发战斗后的结果值
    /// </summary>
    private bool join_battle_key_value;


    // Use this for initialization

    public void Set_Prev_Door(string _d)
    {
        prev_door = _d;
    }


    public string Get_Join_Battle_SceneName()
    {
        return join_battle_sceneName;
    }

    public Vector3 Get_Join_Battle_Pos()
    {
        return join_battle_pos;
    }

    public void Set_Join_Battle_Pos(Vector3 _pos)
    {
        join_battle_pos = _pos;
    }
    public void Set_Join_BattleSceneName(string _sceneName)
    {
        join_battle_sceneName = _sceneName;

    }

    public bool Check_Is_LastBattle(string _join_battle_key)
    {
        if (last_join_battle_key == _join_battle_key)
            return true;
        else
            return false;
    }



    /// <summary>
    /// 返回加入战斗场景之前的场景，并设置玩家的坐标
    /// </summary>
    public void BackToPrevScene()
    {

         SceneManager.LoadScene(  this.join_battle_sceneName );

        //    Debug.Log("BackToPrevScene" + prev_door);
         StartCoroutine(CheckDoorType_And_SetPlayerPos(prev_door));

        //async = SceneManager.LoadSceneAsync(join_battle_sceneName);
        //StartCoroutine(LoadingScene());

    }
    //1,判定从哪个关卡--》到--》现在这个关卡的
    //2,参数《从哪个门，，传送点，，
    //3,到新的关卡，，，需要根据从哪个门，，，设置玩家的位置
    //4,摄像机位置，，，要根据具体逻辑来设定，，
    //5,
    //6,




    public void LoadNext(string _nextscene)
    {
        string real_scene_name = GameSceneDic.GetSceneNameByKey(_nextscene);

        SceneManager.LoadScene(  real_scene_name  );
        try
        {
            GameObject.Find("MainFlowchart").GetComponent<FlowchartView>().IsDoingTalk();
        }
        catch
        {
            Debug.LogError("没有找到MainFlowchart对象");
        }
     

         StartCoroutine(CheckDoorType_And_SetPlayerPos(prev_door));
       
        //async = SceneManager.LoadSceneAsync(real_scene_name);
        //StartCoroutine(LoadingScene());

    }

    private AsyncOperation async;
    private int nowProcess;

    private int asyncProcess;
    IEnumerator LoadSceneAsync(string _sceneName)
    {
        async = SceneManager.LoadSceneAsync(_sceneName);
        async.allowSceneActivation = false;
        yield return async;
        if (async.isDone)
        {
            Debug.Log("Done load");
            StartCoroutine(CheckDoorType_And_SetPlayerPos(prev_door));
        }
    }



    IEnumerator CheckDoorType_And_SetPlayerPos(string _d)
    {
       

        yield return new WaitForSeconds(0.1f);

        if (_d == "普通战斗场景"   )
        {
            Debug.Log("普通战斗场景返回后Check Set Player Pos:" + Get_Join_Battle_Pos());
            SetPlayerPos(Get_Join_Battle_Pos());
            //return;
        }
       else if ( _d == "拉多村南山洞2层战狗战斗")
        {
            Debug.Log("Check Set Player Pos:" + Get_Join_Battle_Pos());
            //SetPlayerPos(Get_Join_Battle_Pos());
         
            try
            {
                SetPlayerPos(new Vector3(0.436F, -2.852F, 0));

                GameObject.Find("PlayerManagerView").GetComponent<PlayerStageManagerView>().TriggerJoinBattleScene();
                GameObject.Find("MainFlowchart").GetComponent<FlowchartView>().Set_TalkToRedLangOne();
                GameObject.Find("NPCAutoContrl").GetComponent<FirstTankNPCCtl>().SetRenderShow();
            }
            catch
            {
                Debug.LogError("刚进入-拉多村南山洞2层战狗战斗-场景，没有找到PlayerManagerView，退出场景时候的时候");
            }

          
           

            
            //return;
        }


        else if (_d == "无" || _d ==null || _d.Trim() =="")
        {
            //自动玩家的坐标，，为，，场景放置的坐标
        }

        else
        {
            Vector3 doorNextPlayerPos = PlayerPositionDic.GetNextPlayerPosByDoor(_d);

            if (doorNextPlayerPos != null && doorNextPlayerPos!= Vector3.zero)
            {

                SetPlayerPos(doorNextPlayerPos);
            }
        }

    }

    public void SetPlayerPos(Vector3 _pos)
    {
        StartCoroutine(Wait_SetPlayerPos(_pos));
    }

    IEnumerator Wait_SetPlayerPos(Vector3 _pos)
    {
        yield return new WaitForSeconds(0.2f);
        GameObject player = GameObject.Find("GameMainPlayer");
      
        Debug.Log("设置玩家的坐标。。。。。。。。。。。。。。。。。。。");
        if (player != null)
        {
            Debug.Log("player不为空,将要设置的坐标为："+ _pos );
            player.transform.position = _pos;
        }
        yield return new WaitForSeconds(0.1f);
        GameObject  camera_m = GameObject.Find("Main Camera");
        if (camera_m != null)
        {
            CameraManager.Instance.Set_Flag(true);
        }
    }


    // Update is called once per frame
    void Update()
    {
        

    }


  
    private IEnumerator LoadingScene()
    {
        async.allowSceneActivation = false;  //如果加载完成，也不进入场景  

        int toProgress = 0;
        int showProgress = 0;

        //测试了一下，进度最大就是0.9  
        while (async.progress < 0.9f)
        {
            toProgress = (int)(async.progress * 100);


            while (showProgress < toProgress)
            {
                showProgress++;
               // setProgressValue(showProgress);
                yield return new WaitForEndOfFrame(); //等待一帧  
            }
        }


        //计算0.9---1   其实0.9就是加载好了，我估计真正进入到场景是1    
        toProgress = 100;

        while (showProgress < toProgress)
        {
            showProgress++;
           // setProgressValue(showProgress);
            yield return new WaitForEndOfFrame(); //等待一帧  
        }

        async.allowSceneActivation = true;  //如果加载完成，可以进入场景  

        StartCoroutine(CheckDoorType_And_SetPlayerPos(prev_door));
    }


}
